package com.lzx.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

public class FileUtil {

	// 随即生成文件名
	public static String getRandomFileName() {
		StringBuffer buffer = new StringBuffer(
				"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
		StringBuffer sb = new StringBuffer();
		Random r = new Random();
		int range = buffer.length();
		for (int i = 0; i < 10; i++) {
			sb.append(buffer.charAt(r.nextInt(range)));
		}

		SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddhhmmss");
		String strCreateTime = fmt.format(new Date().getTime()); // 文件创建日期
		return strCreateTime + sb.toString();
	}

	/**
	 * 保存文件
	 */
	public static void saveFile(InputStream stream, String filePath,
			String fineName) {
		OutputStream bos = null; // 文件输出流
		try {

			File file = new File(filePath);
			if (!file.exists()) {
				file.mkdirs();
			}
			file = new File(filePath, fineName);
			bos = new FileOutputStream(file); // 通过输出流构建文件
			int bytesRead = 0; // 阅读输入文件流的标识
			byte[] buffer = new byte[1024];
			// 读取输入流
			while ((bytesRead = stream.read(buffer, 0, buffer.length)) != -1) {
				bos.write(buffer, 0, bytesRead);// 将文件写入服务器
			}
		} catch (Exception e) {
		} finally {
			try {
				if (bos != null)
					bos.close();
				if (stream != null)
					stream.close();
			} catch (Exception e1) {
			}
		}
	}
}
